#include "com.h"
#include "stdio.h"
#include "stddef.h"
#include "app_cmd.h"
#include "stdbool.h"

static UartRxBuf g_uart_rx_buff[kUartMax];

//get one byte from uart
void UartOnReceiveNewByte(UartID port, char ch)
{
  int next_index; 

  next_index=g_uart_rx_buff[port].last_rx_index;
  next_index ++;
  
  if (next_index >= RX_BUFF_SIZE){
    next_index = 0;
  }
  
  //if buff is full, return
  if (next_index == g_uart_rx_buff[port].first_rx_index){
    //not save the data
  }else{
    //save it
    g_uart_rx_buff[port].rx_buff[g_uart_rx_buff[port].last_rx_index] = ch;
    g_uart_rx_buff[port].last_rx_index  = next_index;          
  }

  //set new byte flag
  g_uart_rx_buff[port].new_data_flag = true;

}

int UartReceivedBufferSize(UartID uart_port)
{
  int size;
  size = g_uart_rx_buff[uart_port].last_rx_index - g_uart_rx_buff[uart_port].first_rx_index;
  if (size < 0)
  {
      size += RX_BUFF_SIZE;
  }

  return size;
}

char UartReceiveByte(UartID uart_port)
{
  char ret;
  int first_index;

  //wait buff not empty
  //while(g_uart_rx_buff[uart_port].first_rx_index == g_uart_rx_buff[uart_port].last_rx_index)
  {
  };

  //get one char
  first_index = g_uart_rx_buff[uart_port].first_rx_index;
  ret = g_uart_rx_buff[uart_port].rx_buff[first_index];
  //move to next index
  first_index++;
  if(first_index >= RX_BUFF_SIZE)
  {
      first_index = 0;
  }
  g_uart_rx_buff[uart_port].first_rx_index = first_index;

  return ret;
}

bool UartGetNewDataFlag(UartID uart_port)
{
  return g_uart_rx_buff[uart_port].new_data_flag;
}

void UartClearNewDataFlag(UartID uart_port)
{
  g_uart_rx_buff[uart_port].new_data_flag = false;
}

void ComHandleNewReceiveChar(UartID com)
{
  int buff_size;

  buff_size = UartReceivedBufferSize(com);

  if (buff_size>0){
    int i;
    char a;
    for(i=0; i<buff_size; i++){
      //get the receive char
      a = UartReceiveByte(com);
      if (com == kUart0){
        app_cmd_on_get_byte(a);//CommOnRecvOneByteFromInternalCom(a);
      }else{
        ;
      }
    }
  }
}
